package org.ru.mse10.cvis.service;

import java.util.Date;

import javax.annotation.Resource;
import javax.ejb.ScheduleExpression;
import javax.ejb.Stateless;
import javax.ejb.Timeout;
import javax.ejb.Timer;
import javax.ejb.TimerConfig;
import javax.ejb.TimerService;

/**
 * The Class TimerScheduler.
 */
@Stateless
public class TimerScheduler {

	/** The timer service. */
	@Resource
	private TimerService timerService;

	/**
	 * Schedule task.
	 * 
	 * @param calendarSchedule
	 *            the calendar schedule
	 * @param taskName
	 *            the task name
	 */
	public void scheduleTask(ScheduleExpression calendarSchedule,
			String taskName) {
		// TimerConfig can be passed to the timer service, during timer
		// creation,
		// to specify whether the timer is persistent and also pass any
		// additional
		// Serializable info.
		TimerConfig timerConfig = new TimerConfig();

		// by default, timers are persistent. So we don't really have to
		// set the persistence property on the TimerConfig. It's done here,
		// just to demonstrate the usage
		timerConfig.setPersistent(true);

		// set the "info" to be passed to the timers
		timerConfig.setInfo(taskName);

		// Now, use the injected timerservice to create a timer instance,
		// for the passed schedule and the timer config
		Timer timer = this.timerService.createCalendarTimer(calendarSchedule,
				timerConfig);

		// that's it, we are done. The timer is now created and started (on
		// successful completion
		// of this method). When the scheduled timeout occurs, a method in this
		// bean which is marked
		// as the timeout callback method will be invoked.
	}

	/**
	 * This method will be invoked by the server when a scheduled timeout occurs
	 * for timer(s) created through the timerservice corresponding to this bean.
	 * 
	 * @param timer
	 *            The {@link Timer} for which the timeout occurred
	 */
	@Timeout
	private void onTimeout(Timer timer) {
		// do some task here. for now, let's just print out to System.out
		System.out.println("Timeout method invoked at " + new Date()
				+ " for bean " + this.getClass().getSimpleName());
	}

}
